# -*- coding:utf-8 -*-
import json
import requests
import csv
'''
功能：食物功效接口:[查询某食物是否能补充营养素或营养素的占比]：https://api.icarbonx.com/nlp/api/v1.0/nutri_food_qa
思路：
1、从csv中读取文件[food_supplement_nutrient_init]，作为食物功效接口的参数
2、保存接口响应结果的数据到csv文件

'''
class food_supplement_nutrient():


    def login_token(self):
        # 初始化登录接口
        login_url = 'https://api.icarbonx.com/oauth2/token?grant_type=password&sms_verify=true'
        login_header = {"Authorization": "Basic Y29tLm1ldW0uY29hY2guaXBob25lOjdmYTYyZmFmYzgxZTgwMzY="}
        login_data = {
            "username": "15012345678",
            "password": "888888",
            "appName": "health-buddy",
            "grant_type": "password",
            "sms_verify": "true"
        }
        # 登录请求接口
        r_login = requests.post(url=login_url, data=login_data, headers=login_header)
        # # 获取登录的响应报文
        # print(r_login.text)
        # login_response = json.loads(r_login.text)
        # # 保存登录的token信息
        # access_token = login_response['access_token']
        token = r_login.json()['access_token']
        print(token)
        '''请求接口获取token值'''
        return token

    def Test_food_supplement_nutrient(self):

        # 初始化
        food_flag_init = 0
        food_error_init = 0
        food_fail_init = 0

        # 读取csv文件,鉴于接口token问题，分成两个表格来进行批量操作 --food_effect_init_second --food_effect_init_first
        with open('E:\\test\\HB\\food_supplement_nutrient_init.csv', 'r') as csvFile:
            reader = csv.reader(csvFile)
            print(type(reader))
            next(reader)
            for row in reader:
                print(row)
                print(type(row))
                print(row[0])
                print(type(row[0]))

                # 食物qa问答接口的请求参数msg
                food_msg = {"msg": row[0]}
                print(food_msg)


                food_headers = {"Authorization": "Bearer " + self.login_token()}
                # 食物量词的url
                food_url = 'https://api.icarbonx.com/nlp/api/v1.0/nutri_food_qa'
                # qa问答模型接口请求
                r_food = requests.post(url=food_url, data=food_msg, headers=food_headers)
                # 获取响应报文
                print(r_food.text)
                # 转换响应结果为dict格式
                food_response = json.loads(r_food.text)
                print(food_response)
                print(type(food_response))

                # 判断响应结果是否为空,不为空，则获取food和name的名称,此处的响应结果是json
                if food_response:
                    print(food_response)
                    food_flag_init = food_flag_init + 1
                    print("食物营养素占比或补充营养素识别成功%d" % food_flag_init)
                    food_response_all = food_response['text']


                    food_effect_data = ['food_msg','food_nutrient']

                    with open('E:\\test\\HB\\food_supplement_nutrient_all.csv', 'a+', encoding='utf-8-sig') as ff:
                        food_effect_data[0] = row[0]
                        # 将返回结果中的逗号删除，避免换行
                        print(food_response_all)
                        s_food = food_response_all.replace(",", "")
                        food_effect_data[1] = s_food

                        ff.write(','.join(food_effect_data))
                        ff.write('\n')
                        ff.close()
                else:
                    food_error_init = food_error_init + 1
                    print("食物营养素占比或补充营养素返回结果是空，可能未识别到食物名称%d"%food_error_init)
                    food_effect_fail = ['food_msg']
                    with open('E:\\test\\HB\\food_supplement_nutrient_fail.csv', 'a+', encoding='utf-8-sig') as fk:
                        food_effect_fail[0] = row[0]
                        fk.write(','.join(food_effect_fail))
                        fk.write('\n')
                        fk.close()

        csvFile.close()

if __name__ == '__main__':
    fd = food_supplement_nutrient()
    fd.Test_food_supplement_nutrient()
